package org.wii.base.web;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.wii.base.context.HttpContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tanghong on 2022/12/23
 */
@Slf4j
public class InitParameterHandler implements HandlerInterceptor {
    /**
     * API请求的灰度标识
     */
    public static final String X_WG_GRAY_LABEL = "X-IWII-GRAY-LAB";
    /**
     * API流量的环境标识
     */
    public static final String X_WG_ENV = "X-IWII-ENV";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String> headers = new HashMap<>(2);
        String grayLabel = request.getHeader(X_WG_GRAY_LABEL);
        String env = request.getHeader(X_WG_ENV);
        if (StrUtil.isNotBlank(grayLabel)) {
            headers.put(X_WG_GRAY_LABEL, grayLabel);
        }
        if (StrUtil.isNotBlank(env)) {
            headers.put(X_WG_ENV, env);
        }
        //log.info("==>>IWII正在运行...");
        HttpContextHolder.setHttpHeaders(headers);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HttpContextHolder.removeHttpHeaders();
    }

}
